package cn.vendpay.com.task;

import cn.vendcommon.com.entity.VideoItem;
import cn.vendpay.com.service.VideoService;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务, 每次去数据库取LimitNum条视频, 处理视频并执行扣费
 * @author Eleven
 */
@Component
public class ScheduledTask {
    private final static int limitNum = 10;

    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private VideoService videoService;

    @PostConstruct
    public void init() {
        // 创建一个核心线程数为2的线程池
        scheduledExecutorService = Executors.newScheduledThreadPool(2);
    }

    /**
     * 使用线程池执行周期任务
     */
    public void scheduleAtFixedRate(Runnable task, long initialDelay, long period) {
        scheduledExecutorService.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }

    /**
     * 使用线程池执行一次性任务
     */
    public void scheduleWithDelay(Runnable task, long delaySeconds) {
        scheduledExecutorService.schedule(task, delaySeconds, TimeUnit.SECONDS);
    }

    /**
     * 半夜时间段 0:00~6:00，每 3 小时执行一次
     */
    @Scheduled(cron = "0 0 0,3,6 * * ?")
    public void nightTask() {
        System.out.println("半夜任务执行：" + System.currentTimeMillis());
        scheduledExecutorService.execute(this::handleVideoAndDeduction);
    }

    /**
     * 白天和晚上 6:00~23:00，每 1 小时执行一次
     */
    @Scheduled(cron = "0 0 7-23/1 * * ?")
    public void dayAndEveningTask() {
        System.out.println("白天/晚上任务执行：" + System.currentTimeMillis());
        // 业务逻辑
        scheduledExecutorService.execute(this::handleVideoAndDeduction);
    }

    // 业务逻辑：处理视频并执行扣费
    public void handleVideoAndDeduction() {
        // 获取视频信息
        List<VideoItem> videoItems = videoService.getVideoItemsByStatusLimitNum(0,limitNum);
        if (CollectionUtils.isEmpty(videoItems)) {
            return;
        }
        for (VideoItem videoItem : videoItems) {
            boolean status = videoService.videoStartTestByUrl(videoItem.getUserId(),videoItem.getUrl(), videoItem.getMachineId(), 10);
            if (status){
                // 更新视频状态为处理完成
                videoItem.setProcessStatus(1);
            } else {
                // 更新视频状态为处理失败
                videoItem.setProcessStatus(0);
            }
        }
        // 统一更新视频状态为处理完成
        videoService.updateStatus(videoItems);
    }

    @PreDestroy
    public void destroy() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }



}
